package cn.nb12.xbox.utils;

import java.io.StringReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 查询游戏接口
 * @author yh
 *
 */
public class FindGameUtil {
	
	private static Logger log=LoggerFactory.getLogger(FindGameUtil.class);
	
	/**
	 * 接口链接
	 */
	public final static String url="https://www.microsoft.com/services/api/v3/suggest?market=<market>&clientId=<clientId>&sources=Microsoft-Terms,Iris-Products,DCatAll-Products&filter=ExcludeDCatProducts:DCatDevices-Products,DCatSoftware-Products,DCatBundles-Products&counts=5,1,5&query=<queryStr>";
	
	/**
	 * 获得搜索的游戏的代码列表
	 * @param clientId
	 * @param queryStr
	 * @return
	 */
	public static List<String> getGames(String clientId,String queryStr,String market){
		String response;
		try {
			Map<String,String> headers=new HashMap<>();
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0");
			headers.put("Content-Type", "application/json; charset=utf-8");
			response = RequestUtil.sendGet(url.replaceAll("<clientId>", clientId).replaceAll("<queryStr>", URLEncoder.encode(queryStr,"UTF-8")).replaceAll("<market>", market),headers,"UTF-8");
			
			// 解析books.xml文件
	        // 创建SAXReader的对象reader
	        SAXReader reader = new SAXReader();
	        // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            Document document = reader.read(new StringReader(response));
            // 通过document对象获取根节点SuggestResponse
            Element suggestResponse = document.getRootElement();
            //获得返回列表
            Element element = suggestResponse.element("ResultSets");
            if(element!=null) {
            	//获得结果集
            	Element element2 = element.element("SuggestResults");
            	if(element2!=null) {
            		//获得建议的结果
            		Element element3 = element2.element("Suggests");
            		if(element3!=null) {
            			//获得列表
            			@SuppressWarnings("unchecked")
						List<Element> elements =(List<Element>)element3.elements("Product");
            			if(elements!=null && elements.size()>0) {
            				List<String> data=new ArrayList<>();
            				for (Element element4 : elements) {
            					if("Games".equals(element4.element("Source").getText().trim())) {
									String url=element4.element("Url").getText().trim();
            						try {
            							data.add(url.substring(url.lastIndexOf("/")+1,url.length()));
									} catch (Exception e) {
										log.error("获取游戏链接错误:"+queryStr,e);
									}
            					}
								else {
									log.info("不是游戏");
								}
							}
            				return data;
            			}
            		}
            	}
            }
		} catch (Exception e) {
			throw new RuntimeException("获取游戏信息出现异常",e);
		}
		return null;
	}
	
	public static void main(String[] args) {
		List<String> games = getGames("7F27B536-CF6B-4C65-8638-A0F8CBDFCA65","Battlefield","zh-hk");
		for (String string : games) {
			System.out.println(string);
		}
	}
}
